package model;

import java.util.ArrayList;
import java.util.List;

public class TableModel {
	private ArrayList<CardStack> data;
	public TableModel() {
		data = new ArrayList<CardStack>();
		init();
	}
	private void init() {
		CardStack stack = new CardStack(100, 100);
		for(int n=1; n<=13; n++) {
			stack.push(new Card(n, Suit.SPADE));
			stack.push(new Card(n, Suit.DIAMOND));
			stack.push(new Card(n, Suit.HEART));
			stack.push(new Card(n, Suit.CLUB));
		}
		data.add(stack);
	}
	
	public ArrayList<CardStack> getCardStacks()
	{
		return data;
	}
	
	/**
	 * Take out sub-stack of size numSelected from mainStack. 
	 * If mainStack is empty, delete from table list of stacks
	 * Returns the new stack.
	 */
	public CardStack moveSubStack(CardStack fromStack, int numSelected, int x, int y)
	{
		CardStack toStack = new CardStack(x,y,fromStack.getFaceUp());
		data.add(toStack);
		moveSubStack(fromStack, numSelected, toStack);
		return toStack;
	}
	
	public void moveSubStack(CardStack fromStack, int numSelected, CardStack toStack)
	{
		if(!data.contains(fromStack))
			System.err.println("ERROR: invalid fromStack argument for moveSubStack() in TableModel");
		if(numSelected>fromStack.size()) 
			System.err.println("ERROR: invalid numSelected argument for moveSubStack() in TableModel");
		if(fromStack==toStack) 
			return;
		
		List<Card> oldStack = fromStack.getCards();
		toStack.getCards().addAll(oldStack.subList(oldStack.size()-numSelected, oldStack.size()));
		for(int n=0; n<numSelected; n++)
			fromStack.pop();
		
		if (fromStack.size() == 0)
			data.remove(fromStack);
		
		
		
		System.out.println(this.toString()); //for debugging
	}

	public String toString() {
		String ret = "";
		for(CardStack stack : data) {
			ret+=stack.size()+" cards at ("+stack.getX()+ ","+stack.getY()+")" + '\n';
		}
		return ret;
	}
}
